package com.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;

import com.entity.OrdersEntity;
import com.utils.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.annotation.IgnoreAuth;

import com.entity.ShangpinxinxiEntity;
import com.entity.view.ShangpinxinxiView;
import com.entity.UserEntity;

import com.service.ShangpinxinxiService;
import com.service.TokenService;
import com.service.UserService;
import com.service.OrdersService;
import com.utils.PageUtils;
import com.utils.R;
import com.utils.MD5Util;
import com.utils.MPUtil;
import com.utils.CommonUtil;


/**
 * 商品信息
 * 后端接口
 * @author 
 * @email 
 * @date 2021-03-20 16:03:02
 */
@RestController
@RequestMapping("/shangpinxinxi")
public class ShangpinxinxiController {
    @Autowired
    private ShangpinxinxiService shangpinxinxiService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private OrdersService orderService;

    /**
     * 后端列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params,ShangpinxinxiEntity shangpinxinxi,
		HttpServletRequest request){
		String tableName = request.getSession().getAttribute("tableName").toString();
		if(tableName.equals("shangjia")) {
			shangpinxinxi.setZhanghao((String)request.getSession().getAttribute("username"));
		}
        EntityWrapper<ShangpinxinxiEntity> ew = new EntityWrapper<ShangpinxinxiEntity>();
		PageUtils page = shangpinxinxiService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, shangpinxinxi), params), params));

        return R.ok().put("data", page);
    }
    
    /**
     * 前端列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,ShangpinxinxiEntity shangpinxinxi, 
                  HttpServletRequest request){
        EntityWrapper<ShangpinxinxiEntity> ew = new EntityWrapper<ShangpinxinxiEntity>();
        
        // 添加查询条件
        if(shangpinxinxi != null) {
            if(shangpinxinxi.getShangpinmingcheng() != null) {
                ew.like("shangpinmingcheng", shangpinxinxi.getShangpinmingcheng());
            }
            if(shangpinxinxi.getLeibie() != null) {
                ew.eq("leibie", shangpinxinxi.getLeibie());
            }
        }
        
        // 默认按创建时间倒序排序
        ew.orderBy("addtime", false);
        
        // 分页查询
        PageUtils page = shangpinxinxiService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, shangpinxinxi), params), params));
        
        return R.ok().put("data", page);
    }

	/**
     * 列表
     */
    @RequestMapping("/lists")
    public R list( ShangpinxinxiEntity shangpinxinxi){
       	EntityWrapper<ShangpinxinxiEntity> ew = new EntityWrapper<ShangpinxinxiEntity>();
      	ew.allEq(MPUtil.allEQMapPre( shangpinxinxi, "shangpinxinxi")); 
        return R.ok().put("data", shangpinxinxiService.selectListView(ew));
    }

	 /**
     * 查询
     */
    @RequestMapping("/query")
    public R query(ShangpinxinxiEntity shangpinxinxi){
        EntityWrapper< ShangpinxinxiEntity> ew = new EntityWrapper< ShangpinxinxiEntity>();
 		ew.allEq(MPUtil.allEQMapPre( shangpinxinxi, "shangpinxinxi")); 
		ShangpinxinxiView shangpinxinxiView =  shangpinxinxiService.selectView(ew);
		return R.ok("查询商品信息成功").put("data", shangpinxinxiView);
    }
	
    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        ShangpinxinxiEntity shangpinxinxi = shangpinxinxiService.selectById(id);
		shangpinxinxi.setClicknum(shangpinxinxi.getClicknum()+1);
		shangpinxinxi.setClicktime(new Date());
		shangpinxinxiService.updateById(shangpinxinxi);
        return R.ok().put("data", shangpinxinxi);
    }

    /**
     * 前端详情
     */
	@IgnoreAuth
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id){
        ShangpinxinxiEntity shangpinxinxi = shangpinxinxiService.selectById(id);
		shangpinxinxi.setClicknum(shangpinxinxi.getClicknum()+1);
		shangpinxinxi.setClicktime(new Date());
		shangpinxinxiService.updateById(shangpinxinxi);
        return R.ok().put("data", shangpinxinxi);
    }
    


    /**
     * 赞或踩
     */
    @RequestMapping("/thumbsup/{id}")
    public R vote(@PathVariable("id") String id,String type){
        ShangpinxinxiEntity shangpinxinxi = shangpinxinxiService.selectById(id);
        if(type.equals("1")) {
        	shangpinxinxi.setThumbsupnum(shangpinxinxi.getThumbsupnum()+1);
        } else {
        	shangpinxinxi.setCrazilynum(shangpinxinxi.getCrazilynum()+1);
        }
        shangpinxinxiService.updateById(shangpinxinxi);
        return R.ok("投票成功");
    }

    /**
     * 后端保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody ShangpinxinxiEntity shangpinxinxi, HttpServletRequest request){
    	shangpinxinxi.setId(new Date().getTime()+new Double(Math.floor(Math.random()*1000)).longValue());
    	//ValidatorUtils.validateEntity(shangpinxinxi);
        shangpinxinxiService.insert(shangpinxinxi);
        return R.ok();
    }
    
    /**
     * 前端保存
     */
    @RequestMapping("/add")
    public R add(@RequestBody ShangpinxinxiEntity shangpinxinxi, HttpServletRequest request){
    	shangpinxinxi.setId(new Date().getTime()+new Double(Math.floor(Math.random()*1000)).longValue());
    	//ValidatorUtils.validateEntity(shangpinxinxi);
    	
    	// 设置月售销量默认值为0
    	if(shangpinxinxi.getYueshouxiaoliang() == null) {
    		shangpinxinxi.setYueshouxiaoliang("0");
    	}
    	
    	// 设置点击次数默认值为0
    	if(shangpinxinxi.getClicknum() == null) {
    		shangpinxinxi.setClicknum(0);
    	}
    	
        shangpinxinxiService.insert(shangpinxinxi);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody ShangpinxinxiEntity shangpinxinxi, HttpServletRequest request){
        //ValidatorUtils.validateEntity(shangpinxinxi);
        shangpinxinxiService.updateById(shangpinxinxi);//全部更新
        return R.ok();
    }
    

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        shangpinxinxiService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }
    
    /**
     * 提醒接口
     */
	@RequestMapping("/remind/{columnName}/{type}")
	public R remindCount(@PathVariable("columnName") String columnName, HttpServletRequest request, 
						 @PathVariable("type") String type,@RequestParam Map<String, Object> map) {
		map.put("column", columnName);
		map.put("type", type);
		
		if(type.equals("2")) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			Date remindStartDate = null;
			Date remindEndDate = null;
			if(map.get("remindstart")!=null) {
				Integer remindStart = Integer.parseInt(map.get("remindstart").toString());
				c.setTime(new Date()); 
				c.add(Calendar.DAY_OF_MONTH,remindStart);
				remindStartDate = c.getTime();
				map.put("remindstart", sdf.format(remindStartDate));
			}
			if(map.get("remindend")!=null) {
				Integer remindEnd = Integer.parseInt(map.get("remindend").toString());
				c.setTime(new Date());
				c.add(Calendar.DAY_OF_MONTH,remindEnd);
				remindEndDate = c.getTime();
				map.put("remindend", sdf.format(remindEndDate));
			}
		}
		
		Wrapper<ShangpinxinxiEntity> wrapper = new EntityWrapper<ShangpinxinxiEntity>();
		if(map.get("remindstart")!=null) {
			wrapper.ge(columnName, map.get("remindstart"));
		}
		if(map.get("remindend")!=null) {
			wrapper.le(columnName, map.get("remindend"));
		}

		String tableName = request.getSession().getAttribute("tableName").toString();
		if(tableName.equals("shangjia")) {
			wrapper.eq("zhanghao", (String)request.getSession().getAttribute("username"));
		}

		int count = shangpinxinxiService.selectCount(wrapper);
		return R.ok().put("count", count);
	}
	
	/**
     * 前端智能排序 推荐算法，基于月售销量和点击次数
     */
	@IgnoreAuth
    @RequestMapping("/autoSort")
    public R autoSort(@RequestParam Map<String, Object> params, ShangpinxinxiEntity shangpinxinxi, 
                     HttpServletRequest request, String pre) {
        // 获取所有商品
        EntityWrapper<ShangpinxinxiEntity> allProductsEw = new EntityWrapper<ShangpinxinxiEntity>();
        List<ShangpinxinxiEntity> allProducts = shangpinxinxiService.selectList(allProductsEw);

        // 计算每个商品的推荐得分
        List<Map<String, Object>> scoredProducts = new ArrayList<>();
        for (ShangpinxinxiEntity product : allProducts) {
            double score = 0.0;
            
            // 1. 月售销量得分 (权重0.7)
            // 使用商品的月售销量字段
            Integer monthlySales = Integer.valueOf(product.getYueshouxiaoliang());
            if (monthlySales != null) {
                score += monthlySales * 0.7;
            }
            
            // 2. 点击次数得分 (权重0.3)
            // 使用商品的点击次数字段
            Integer clickCount = product.getClicknum();
            if (clickCount != null) {
                score += clickCount * 0.3;
            }
            
            Map<String, Object> scoredProduct = new HashMap<>();
            scoredProduct.put("product", product);
            scoredProduct.put("score", score);
            scoredProducts.add(scoredProduct);
        }
        
        // 按得分排序
        scoredProducts.sort((a, b) -> 
            Double.compare((Double) b.get("score"), (Double) a.get("score")));
        
        // 获取分页参数
        int page = Integer.parseInt(params.get("page").toString());
        int limit = Integer.parseInt(params.get("limit").toString());
        int start = (page - 1) * limit;
        int end = Math.min(start + limit, scoredProducts.size());
        
        // 构建分页结果
        List<Map<String, Object>> pageList = scoredProducts.subList(start, end);
        List<ShangpinxinxiEntity> resultList = pageList.stream()
            .map(item -> (ShangpinxinxiEntity) item.get("product"))
            .collect(Collectors.toList());
        
        // 构建分页对象
        PageUtils pageUtils = new PageUtils(resultList, scoredProducts.size(), limit, page);
        
        return R.ok().put("data", pageUtils);
    }



}
